package com.cloud.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.common.model.entity.EmailTemplates;
import com.cloud.common.model.enums.MailTemplatesEnum;
import com.cloud.common.model.request.EmailConfig;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 邮件工具
 */
@Component
@AllArgsConstructor
@Service
public class EmailUtil {

    public boolean sendMail(EmailConfig emailConfig, String bcEmailTemplateStr, MailTemplatesEnum mailTemplatesEnum,
                            String toEmail, JSONObject toValue) {
        try {
            if (StrUtil.isEmpty(toEmail)) {
                return false;
            }
            List<EmailTemplates> emailTemplatesList = JSONUtil.toList(bcEmailTemplateStr, EmailTemplates.class);
            EmailTemplates emailTemplates = emailTemplatesList.stream().
                    filter(t -> t.getAlias().equals(mailTemplatesEnum.getTitle())).
                    findFirst().orElse(new EmailTemplates());

            MailAccount account = new MailAccount();
            BeanUtil.copyProperties(emailConfig, account);
            String content = emailTemplates.getValue();
            //提取参数
            if (null != toValue) {
                Set<Map.Entry<String, Object>> entries = toValue.entrySet();
                for (Map.Entry<String, Object> item : entries) {
                    String key = item.getKey();
                    String value = Convert.toStr(item.getValue());
                    content = content.replace("{" + key + "}", value);
                }
            }
//            MailUtil.send(account, toEmail, emailTemplates.getName(), content, emailConfig.getIsHtml());
            //返回发送内容
            emailConfig.setSendContent(content);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
